/*
 * topological-hex, a program to compute combinatorial hexahedral meshes.
 *
 * Copyright (C) <2018> <Université catholique de Louvain (UCL), Belgique>
 *
 * List of the contributors to the development, description and complete
 * License: see LICENSE file.
 *
 * This program (topological-hex) is free software:
 * you can redistribute it and/or modify it under the terms
 * of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program (see COPYING file).  If not,
 * see <http://www.gnu.org/licenses/>.
 */

#ifndef SPARSE_SET_H_
#define SPARSE_SET_H_

#include <stdint.h>
#include <stdlib.h>
#include "types.h"

/**
 * @addtogroup set
 * @{
 */

/**
 * Set to store integers between 0 and @ref sparse_set::capacity.
 *
 * The implementation guarantees that data[indices[v]] = v and that the first
 * @ref sparse_set::size elements of data are the elements of the set. This
 * allows using the index to quickly check membership.
 */
typedef struct sparse_set {
  /**
   * Values in the set. The first size entry are the elements in the set.
   */
  uint32_t *data;

  uint32_t *indices;

  /**
   * Number of elements of the set.
   */
  uint32_t size;

  /**
   * Maximum number of integers in the set.
   */
  uint32_t capacity;
} sparse_set;

/**
 * Initializes an empty sparse set.
 *
 * @param n Maximum number of elements in the set.
 */
static
error_code sparse_set_init(sparse_set *set, uint32_t n) {
  set->data = malloc(2 * n * sizeof(*set->data));
  if (!set->data) return OUT_OF_MEMORY;

  set->indices = set->data + n;

  set->size = 0;
  set->capacity = n;

  for (uint32_t i = 0; i < n; i++) {
    set->data[i] = set->indices[i] = i;
  }

  return SUCCESS;
}

/**
 * Relesaes all memory used by a sparse set.
 */
static
void sparse_set_release(sparse_set *set) {
  free(set->data);
}

/**
 * Inserts a value into a sparse set.
 */
static
void sparse_set_insert(sparse_set *set, uint32_t x) {
  if (set->indices[x] >= set->size) {
    uint32_t y = set->data[set->size];
    set->indices[y] = set->indices[x];
    set->indices[x] = set->size;

    set->data[set->size] = x;
    set->data[set->indices[y]] = y;

    set->size++;
  }
}

/**
 * Removes a value from a sparse set.
 */
static
void sparse_set_remove(sparse_set *set, uint32_t x) {
  if (set->indices[x] < set->size) {
    uint32_t y = set->data[set->size - 1];

    set->indices[y] = set->indices[x];
    set->indices[x] = set->size - 1;

    set->data[set->size - 1] = x;
    set->data[set->indices[y]] = y;

    set->size--;
  }
}

/**
 * @}
 */

#endif
